package com.jerry.ReadWriteLock;

public class WriteLock implements Lock {

    private ReadWriteLock readWriteLock;

    public WriteLock(ReadWriteLock readWriteLock) {
        this.readWriteLock = readWriteLock;
    }

    @Override
    public void lock() throws InterruptedException {
        synchronized (this.readWriteLock.getMutex()){
            //刚获得锁，先增加等待写数
            this.readWriteLock.increaseWaitingWriter();
            try {
                //如果已经存在在写或者在读的，则阻塞当前线程
                while (this.readWriteLock.getWritingWriter() > 0 || this.readWriteLock.getReadingReader() > 0) {
                        this.readWriteLock.getMutex().wait();

                }
            }finally {
                //无论是否执行，都要将原有的等待写减1
                this.readWriteLock.decreaseWaitingWriter();
            }
            //执行当前线程时，增加正在写数
          this.readWriteLock.increaseWritingWriter();

      }
    }

    @Override
    public void unlock() {
        synchronized (this.readWriteLock.getMutex()){
            //解锁时，先减少正在写数
            this.readWriteLock.decreaseWritingWriter();
            this.readWriteLock.changePrefer(false);
            this.readWriteLock.getMutex().notifyAll();

        }
    }
}
